package cn.elwy.rcp.ui.util;

import org.eclipse.jface.resource.ColorDescriptor;
import org.eclipse.jface.resource.ColorRegistry;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;

/**
 * 获取颜色工具类
 * @author huangsq
 * @version 2.0, 2015-02-19
 * @since 1.0, 2015-02-19
 */
public class ColorUtil {

  private static final ColorRegistry colorRegistry = JFaceResources.getColorRegistry();

  // 将构造方法设置为private,禁止创建该类的实例
  private ColorUtil() {
  }

  /**
   * 根据RGB值获取颜色对象
   * @param r
   * @param g
   * @param b
   * @return
   */
  public static Color getColor(int r, int g, int b) {
    String rgb = r + "|" + g + "|" + b;
    if (!colorRegistry.hasValueFor(rgb)) {
      colorRegistry.put(rgb, new RGB(r, g, b));
    }
    return colorRegistry.get(rgb);
  }

  /**
   * 根据RGB获取颜色对象
   * @param symbolicName 颜色RGB,格式"COLOR:255-255-255"
   * @return
   */
  public static Color getColor(String symbolicName) {
    Color color = colorRegistry.get(symbolicName);
    if (color == null || color.isDisposed()) {
      ColorDescriptor colorDescriptor = colorRegistry.getColorDescriptor(symbolicName, null);
      if (colorDescriptor != null) {
        color = colorDescriptor.createColor(Display.getCurrent());
        colorRegistry.put(symbolicName, color.getRGB());
      } else {
        try {
          String rgb[] = symbolicName.split("|");
          if (rgb != null && rgb.length == 3) {
            int r = Integer.parseInt(rgb[0]);
            int g = Integer.parseInt(rgb[1]);
            int b = Integer.parseInt(rgb[2]);
            colorRegistry.put(symbolicName, new RGB(r, g, b));
            color = colorRegistry.get(symbolicName);
          }
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return color;
  }

}
